package com.southwind.springboottest.controller;

import com.southwind.springboottest.entity.User;
import com.southwind.springboottest.repository.UserRepository;
import javax.validation.ConstraintViolationException;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

@RestController
@RequestMapping("/user")
public class UserHandler {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/findAll/{page}/{size}")
    public ResponseEntity<Map<String, Object>> findAll(
            @PathVariable("page") @Min(0) Integer page,
            @PathVariable("size") @Min(1) @Max(100) Integer size) {
        try {
            PageRequest request = PageRequest.of(page, size, Sort.by("userid").ascending());
            System.out.println("分页请求参数: "+request);
            
            Page<User> result = userRepository.findAll(request);
            System.out.println("查询结果: "+result.getContent().size()+"条记录");
            
            Map<String, Object> response = new HashMap<>();
            response.put("data", result.getContent());
            response.put("total", result.getTotalElements());
            response.put("page", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("分页查询异常: "+e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", "服务器内部错误"));
        }
    }

    @PostMapping("/save")
    @Transactional
    public String save(@RequestBody User user){
        User result = userRepository.save(user);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @GetMapping("/findById/{id}")
    public User findById(@PathVariable("id") Integer id){
        return userRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody User user){
        User result = userRepository.save(user);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){
        userRepository.deleteById(id);
    }

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody User loginUser) {
        Map<String, Object> response = new HashMap<>();
        try {
            User user = userRepository.findByUsernameAndPassword(
                loginUser.getUsername(), 
                loginUser.getPassword()
            );
            
            if (user == null) {
                response.put("status", "error");
                response.put("message", "用户名或密码错误");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            response.put("status", "success");
            response.put("id", user.getUserid());
            response.put("username", user.getUsername());
            response.put("role", user.getRole());
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "登录失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    @GetMapping("/testConnection")
    public ResponseEntity<Map<String, Object>> testConnection() {
        Map<String, Object> response = new HashMap<>();
        try {
            // 测试基础查询
            long count = userRepository.count();
            
            // 测试直接SQL查询
            List<User> users = userRepository.findAll();
            
            response.put("status", "success");
            response.put("table", "user");
            response.put("count", count);
            response.put("sample_data", users.isEmpty() ? "no data" : users.get(0));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}
